package leetcode;

/**
 * Merge Two Sorted Lists
 * 
 * @author zhujb
 *
 *         2017年8月31日
 */
public class leet021 {

	public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

		if (l1 == null) {
			return l2;
		}
		if (l2 == null) {
			return l1;
		}

		ListNode tmp = new ListNode(0);
		ListNode cur = tmp;

		while (l1 != null || l2 != null) {

			if (l1 == null) {
				cur.next = l2;
				l2 = null;
				break;
			} else if (l2 == null) {
				cur.next = l1;
				l1 = null;
				break;
			} else if (l1.val <= l2.val) {
				cur.next = l1;
				cur = cur.next;
				l1 = l1.next;
			} else {
				cur.next = l2;
				cur = cur.next;
				l2 = l2.next;
			}

		}
		return tmp.next;
	}

	public static void main(String[] args) {

		leet021 leet21 = new leet021();

		ListNode l1 = new ListNode(1);
		l1.next = new ListNode(3);
		l1.next.next = new ListNode(5);
		ListNode l2 = new ListNode(2);
		l2.next = new ListNode(4);
		ListNode mergeTwoLists = leet21.mergeTwoLists(l1, l2);

		pr(mergeTwoLists);

	}

	public static void pr(ListNode node) {

		while (node != null) {
			System.out.println(node.val);
			node = node.next;
		}
	}
}

class ListNode {
	int val;
	ListNode next;

	ListNode(int x) {
		val = x;
	}
}